package com.aaa.service;


import com.aaa.dao.PermissionDao;
import com.aaa.dao.UserDao;
import com.aaa.entity.Permission;
import com.aaa.entity.Users;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserService  implements UserDetailsService {
    @Resource
    private UserDao userDao;
    @Resource
    private PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userDao.selectByUsername(username);
        if (users!=null){
            //该用户具有的权限
            Collection<GrantedAuthority> authorities=new ArrayList<>();
            //根据用户id查询该用户具有的权限。
            List<Permission> userid = permissionDao.findByUserid(users.getUserid());
            //把上面的权限封装authorities中----jdk1.8 Stream流--
            authorities=userid.stream()
                                  .map(item->new SimpleGrantedAuthority(item.getPercode()))
                                  .collect(Collectors.toList());
            User user=new User(username,users.getUserpwd(),authorities);
            return user;
        }
        return null;
    }
}
